package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.DeviceReportDataVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 *
 * @author liufan
 * @date 2025-08-22
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-同步设备列表失败");
        }
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY,
                JSONUtil.toJsonStr(response.getProducts()));

    }

    @Override
    public List<ProductVo> allProduct() {
        String products = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StringUtils.isEmpty(products)) {
            return Collections.emptyList();
        }

        return JSONUtil.toList(products, ProductVo.class);
    }

    @Override
    public void rigister(DeviceDto deviceDto) {
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getNodeId, deviceDto.getNodeId());
        if (count(wrapper) > 0) {
            throw new BaseException("设备已存在");
        }
        LambdaQueryWrapper<Device> wrapper2 = Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(wrapper2) > 0) {
            throw new BaseException("设备已存在");
        }
        LambdaQueryWrapper<Device> wrapper3 = Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation());
        if (count(wrapper3) > 0) {
            throw new BaseException("该位置已存在类似设备");
        }

        //IOT中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(deviceDto.getProductKey());
        body.withNodeId(deviceDto.getNodeId());
        body.withDeviceName(deviceDto.getDeviceName());

        AuthInfo authInfo = new AuthInfo();
        //秘钥：利用Hutool工具包的UUID类生成
        String secret = UUID.randomUUID().toString(true);
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse response = client.addDevice(request);

        Device device = new Device();
        BeanUtils.copyProperties(deviceDto, device);

        //加上华为云生成的IotId
        device.setIotId(response.getDeviceId());
        //加上密钥
        device.setSecret(secret);
        save(device);
    }

    @Override
    public DeviceDetailVo getDeviceById(String id) {
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, id);
        Device device = getOne(wrapper);
        if (device == null) {
            return null;
        }
        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtil.copyProperties(device, vo);
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(id);
        ShowDeviceResponse response = client.showDevice(request);
        String activeTime = response.getActiveTime();
        //把华为云平台获取的activeTime时间转换为亚洲上海时间dateTime格式，用一段代码转换
        if (StringUtils.isNotEmpty(activeTime)) {
            LocalDateTime beijingDateTime = LocalDateTime.parse(activeTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"))
                    .atZone(ZoneOffset.UTC)
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setActiveTime(beijingDateTime);
        }

        vo.setDeviceStatus(response.getStatus());
        return vo;
    }

    @Override
    public List<DeviceReportDataVo> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        List<DeviceShadowData> shadow = response.getShadow();
        if (shadow == null || shadow.isEmpty()) {
            return Collections.emptyList();
        }
        Map<String, Object> properties = (Map<String, Object>) shadow.get(0).getReported().getProperties();

        //DeviceReportDataVo reportDataVo = new DeviceReportDataVo();
        String eventTimeStr = shadow.get(0).getReported().getEventTime();
        LocalDateTime reportTime = LocalDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        LocalDateTime eventTime = reportTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        /*LocalDateTime evenDateTime = LocalDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"))
                .atZone(ZoneOffset.UTC)
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();回顾这里的问题*/

        ArrayList<DeviceReportDataVo> list = new ArrayList<>();
        properties.forEach((prop, value) -> {
            DeviceReportDataVo vo = new DeviceReportDataVo();
            vo.setFunctionId(prop);
            vo.setEventTime(eventTime);
            vo.setValue(value);
            list.add(vo);
        });
        return list;
    }

    @Override
    public void deleteById(String iotId) {
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, iotId);
        remove(wrapper);
    }

    @Override
    public void updateByDevice(DeviceDto deviceDto) {
        deviceMapper.updateByDevice(deviceDto);
    }

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-查询产品信息失败");
        }
        return response.getServiceCapabilities();
    }
}
